package com.tencreat.framework.config;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.tencreat.common.annotation.DictName;
import com.tencreat.common.core.domain.entity.SysDictData;
import com.tencreat.common.utils.DictUtils;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 枚举转字典数据
 *
 * @author zixin
 * @company 深圳腾创互联科技有限公司
 * @link https://tencreat.com
 * @since 2023/4/13 16:12
 */

@Configuration
public class EnumConvertDictConfig {

    @PostConstruct
    void enumClassMap() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Set<Class<?>> set = ClassUtil.scanPackage("com.tencreat.common.enums");
        Map<String, String> map = new HashMap<>();
        for (Class<?> item : set) {
            String dictType = AnnotationUtil.getAnnotationValue(item, DictName.class);
            if (StrUtil.isNotBlank(dictType)) {
                String value = map.get(dictType);
                if (StrUtil.isNotBlank(value)) {
                    throw new RuntimeException("@DictName存在相同value");
                }

                // 将枚举存入缓存和redis一起
                List<SysDictData> list = new ArrayList<>();
                Object[] objects = item.getEnumConstants();
                Method getValue = item.getMethod("getValue");
                Method getDesc = item.getMethod("getDesc");
                // TODO 排除掉 Deprecated 的属性
                for (Object obj : objects) {
                    SysDictData sysDictData = new SysDictData();
                    sysDictData.setDictLabel(getDesc.invoke(obj).toString());
                    sysDictData.setDictValue(getValue.invoke(obj).toString());
                    list.add(sysDictData);
                }
                DictUtils.setDictCache(dictType, list);
                map.put(dictType, dictType);
            }
        }
    }

}
